from PyQt6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, 
                           QTreeWidget, QTreeWidgetItem, QSplitter,
                           QStackedWidget)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont, QIcon
from .converters.pdf_converter import PDFConverterWidget
from .converters.pdf_to_image_converter import PDFToImageConverter
from .converters.image_converter import ImageMerger
from .converters.excel_converter import ExcelConverterWidget
from .converters.document_converter import DocumentConverterWidget

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("文件转换工具")
        self.resize(800, 600)
        
        # 创建中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建布局
        layout = QVBoxLayout(central_widget)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 创建分割器
        splitter = QSplitter(Qt.Orientation.Horizontal)
        
        # 创建左侧树状菜单
        self.tree = QTreeWidget()
        self.tree.setHeaderLabel("功能模块")
        self.tree.setMinimumWidth(200)
        self.tree.setMaximumWidth(300)
        
        # 连接展开信号
        self.tree.itemExpanded.connect(self.on_item_expanded)
        self.tree.itemCollapsed.connect(self.on_item_collapsed)
        
        # 设置树状菜单样式
        self.setup_tree_style()
        
        # 创建右侧堆叠部件
        self.stacked_widget = QStackedWidget()
        self.stacked_widget.setMinimumWidth(700)
        self.stacked_widget.setStyleSheet("""
            QStackedWidget {
                background: white;
                padding: 10px;
            }
        """)
        
        # 初始化所有功能页面
        self.init_pages()
        
        # 添加功能模块到树状菜单
        self.init_tree()
        
        # 将部件添加到分割器
        splitter.addWidget(self.tree)
        splitter.addWidget(self.stacked_widget)
        
        # 设置分割器的初始比例
        splitter.setStretchFactor(0, 1)
        splitter.setStretchFactor(1, 4)
        
        # 添加分割器到主布局
        layout.addWidget(splitter)
        
        # 连接树状菜单的点击事件
        self.tree.itemClicked.connect(self.on_tree_item_clicked)
        
        # 设置默认显示的页面为"文档转PDF"
        self.stacked_widget.setCurrentIndex(1)
        
        # 设置左侧树状菜单中对应项目为选中状态
        pdf_category = self.tree.topLevelItem(0)  # PDF转换类别
        self.tree.expandItem(pdf_category)  # 展开PDF转换类别
        doc_to_pdf_item = pdf_category.child(0)  # 文档转PDF项
        doc_to_pdf_item.setBackground(0, Qt.GlobalColor.lightGray)  # 设置选中状态
    
    def setup_tree_style(self):
        # 设置字体
        tree_font = QFont()
        tree_font.setPointSize(10)
        self.tree.setFont(tree_font)
        
        # 设置行高
        self.tree.setStyleSheet("""
            QTreeWidget {
                background-color: #f0f0f0;
                border: none;
                outline: none;
            }
            QTreeWidget::item {
                height: 35px;
                padding: 5px;
                border-radius: 4px;
            }
            QTreeWidget::item:hover {
                background-color: #e0e0e0;
            }
            QTreeWidget::item:selected {
                background-color: #d0d0d0;
                color: black;
            }
            QTreeWidget::branch {
                background-color: transparent;
            }
        """)
        
        # 设置其他树状菜单属性
        self.tree.setAnimated(True)
        self.tree.setIndentation(20)
        self.tree.setHeaderHidden(True)
        
        # 默认收起所有项
        self.tree.collapseAll()
    
    def init_pages(self):
        """初始化各个转换页面"""
        self.pages = {
            "图片合并": ImageMerger("图片合并", "将多张图片合并为PDF文件"),
            "文档转PDF": DocumentConverterWidget("文档转PDF", "将文档转换为PDF格式"),
            "PDF转图片": PDFToImageConverter(),
            "Excel转Markdown": ExcelConverterWidget("Excel转Markdown", "将Excel文件转换为Markdown表格")
        }
        
        # 将页面添加到堆叠部件中
        for widget in self.pages.values():
            self.stacked_widget.addWidget(widget)
    
    def on_item_expanded(self, item):
        """当一个项目被展开时，收起其他所有顶级项目"""
        if item in self.categories:
            # 更改展开项的箭头方向
            item.setText(0, "▼ " + item.text(0)[2:])
            for category in self.categories:
                if category != item:
                    self.tree.collapseItem(category)
                    # 确保其他项显示右箭头
                    if not category.text(0).startswith("▶"):
                        category.setText(0, "▶ " + category.text(0)[2:])
    
    def on_item_collapsed(self, item):
        """当项目被收起时的处理"""
        if item in self.categories:
            # 更改收起项的箭头方向
            if not item.text(0).startswith("▶"):
                item.setText(0, "▶ " + item.text(0)[2:])
    
    def on_tree_item_clicked(self, item, column):
        """处理项目点击事件"""
        parent = item.parent()
        
        if parent is None:
            # 如果点击的是顶层分类项，只处理展开/收起
            if item.isExpanded():
                self.tree.collapseItem(item)
            else:
                self.tree.expandItem(item)
                for category in self.categories:
                    if category != item:
                        self.tree.collapseItem(category)
        else:
            # 只有点击子菜单项（最底层）才切换右侧面板
            if not item.childCount():  # 确保是最底层菜单项
                # 添加选中状态样式
                for category in self.categories:
                    for i in range(category.childCount()):
                        child = category.child(i)
                        child.setBackground(0, Qt.GlobalColor.transparent)
                item.setBackground(0, Qt.GlobalColor.lightGray)
                
                # 获取菜单项文本并切换到对应页面
                item_text = item.text(0)
                if item_text in self.pages:
                    self.stacked_widget.setCurrentIndex(list(self.pages.keys()).index(item_text))
    
    def init_tree(self):
        # PDF转换模块
        pdf_category = self.create_category_item("PDF转换")
        pdf_items = [
            "文档转PDF",
            "PDF转图片"
        ]
        for item in pdf_items:
            self.create_menu_item(pdf_category, item)
        
        # 图片转换模块
        image_category = self.create_category_item("图片转换")
        image_items = [
            "图片合并"
        ]
        for item in image_items:
            self.create_menu_item(image_category, item)
        
        # Excel转换模块
        excel_category = self.create_category_item("Excel转换")
        excel_items = [
            "Excel转Markdown"
        ]
        for item in excel_items:
            self.create_menu_item(excel_category, item)
        
        # 默认收起所有项
        self.tree.collapseAll()
        
        # 存储所有顶级项目的引用
        self.categories = [
            self.tree.topLevelItem(i) 
            for i in range(self.tree.topLevelItemCount())
        ]
    
    def create_category_item(self, text):
        """创建分类项"""
        item = QTreeWidgetItem(self.tree)
        item.setText(0, "▶ " + text)  # 添加向右箭头表示可以展开
        # 设置分类项的字体为粗体
        font = item.font(0)
        font.setBold(True)
        item.setFont(0, font)
        return item
    
    def create_menu_item(self, parent, text):
        """创建菜单项"""
        item = QTreeWidgetItem(parent)
        item.setText(0, text)
        # 设置菜单项的缩进和样式
        item.setTextAlignment(0, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        return item

    def switch_page(self, action):
        """切换页面"""
        page_name = action.text()
        if page_name in self.pages:
            # 获取对应页面的索引
            index = list(self.pages.keys()).index(page_name)
            self.stacked_widget.setCurrentIndex(index) 